<?php
	
class EmailAPI {
	protected $phpMailer;
	protected $subject;
	protected $isError = false;
	protected $applyStandardTemplate = TRUE;
	protected $emailClassification;
	protected $params = NULL;
	
	// Params : Date, Time, Motor ID/ Description , User  , Subject, EMail Content, Email Type 
	
	function __construct($params) {
	   $this->phpMailer = new PHPMailer();
	   $this->initPhpMailer();
	   $this->params = $params;
	}
	
	public function setEmailContent($content) {
		if($this->applyStandardTemplate==TRUE) {
		
			//$dueString = "";//($this->dueDays==0) ? "Due till date" : "Due untill the next {$this->dueDays} days";
		
			//$content = 
		}
		return $content; 
	}
	
	private function initPhpMailer() {
		$this->phpMailer->IsSMTP();
		$this->phpMailer->SMTPDebug  = 1;
		$this->phpMailer->SMTPAuth   = SMTP_AUTH;                  
		$this->phpMailer->Host       = SMTP_HOST;      				
		$this->phpMailer->Port       = SMTP_PORT;                   
		$this->phpMailer->Username   = SMTP_USER;  
		$this->phpMailer->Password   = SMTP_PASSWORD;            
		$this->phpMailer->SetFrom(EMAIL_FROM_EMAIL,EMAIL_FROM_USERNAME);	
	}
	
	private function clearPhpMailer() {
		$this->phpMailer->ClearAddresses();
	}
	
	private function clearAllPhpMailer() {
		$this->phpMailer->ClearAllRecipients();
	}
	
	public function setApplyStandardTemplate($v) {
		$this->applyStandardTemplate = $v;
	}
	
	protected function getAddress($emailClassification){
		$entityId=isset($this->params['entityId']) ? $this->params['entityId'] : NULL;
		switch($emailClassification){
			
			case "daily_summary_email":
			$sql=" 
					SELECT U.userEmail  
					FROM  `users` AS U
					JOIN  `usermapping` AS M
					WHERE U.id = M.userId
					AND M.entityId ={$entityId}
					AND M.userStatus =1
				";
				$result=executeReadQuery($sql);
				return convertObjToArray($result);
			break;
			
			case "individualEmail":
				return isset($this->params['emails']) ? [["userEmail"=>$this->params['emails']]] : NULL;
			break;
			
			default: return NULL;
			
		
		}
	
	}
	
	protected function loadEmailAddresses () {
		
		$addresses=$this->getAddress($this->emailClassification);
		if(!isset($addresses) || count(($addresses))==0 ){
			$isError=TRUE;
			writeToLogFile("error in loading address");
			return;
		}
		
		
		foreach($addresses as $email) {
			$this->phpMailer->AddAddress($email["userEmail"], $email["userEmail"]);
		}
		$this->phpMailer->AddBCC("aranyak.banerjee90@gmail.com", "Aranyak");
		
		
		/*
		// Find out the emails associated with the entity id and add them up individually to the Addresses
		$userList = getUserList($this->entity);
		
		if(count($userList)==0) {
			$this->isError = TRUE;
		} else {
			foreach($userList as $user) {
			
				// Skip if in the exclusion List
				if(is_excluded_from($user->email,$this->emailClassification)) writeToLogFile("Skipping {$user->email} for {$this->emailClassification}");
				if(is_excluded_from($user->email,$this->emailClassification)) continue;
				
				
				$this->phpMailer->AddAddress($user->email, $user->display_name);
			}
		}
		
		// Add these default id's as BCC		
		$this->phpMailer->AddBCC("amit@eetpl.in", "Amit Bhutoria");
		$this->phpMailer->AddBCC("ub@eetpl.in", "Umesh Bhutoria");
		$this->phpMailer->AddBCC("amlan@eetpl.in", "Amlan G Mahapatra");
		*/
	}
	
	protected function loadEmailContent() {
		$html = $this->setEmailContent($this->params['html']);
		$this->phpMailer->MsgHTML($html);	
	}
	
	
	protected function loadEmailSubject() {
		$this->emailClassification = $this->params['emailClassification'];
		$this->phpMailer->Subject = $this->params['subject'];
	}
	
	protected function loadAll() {
		$this->loadEmailSubject();
		$this->loadEmailContent();
		$this->loadEmailAddresses();
	}
	
	public function send() {
		
		$this->loadAll();
		
		if($this->isError) {
			// Return without sending email
			writeToLogFile("Returning without sending email due to error. Params :".json_encode($this->params));
			return;
		}
		
		if(!$this->phpMailer->Send()) {
			$log = "Unable to send email due to the following error :{$this->phpMailer->ErrorInfo}";
			writeToLogFile($log);
			sendMailNotification($log);
			return FALSE;
		}
		
		return TRUE;
	}
}